<script lang="ts" setup>
import { Overlay, showConfirmDialog, showFailToast, showSuccessToast } from 'vant'
import { ContactApi } from '~/api/ContactApi';
import { Common } from '~/common'
import type { ContactModel } from '~/model'

const props = withDefaults(defineProps<{
  contact: ContactModel
  size: number
  canClick: boolean
  canUnload: boolean
}>(), {
  canUnload: false,
  canClick: false,
})

const fileInput = ref(null as null | HTMLInputElement)

function showUploadMenu() {
  // e.stopPropagation()
  if (!props.canUnload) {
    return
  }
  showConfirmDialog({
    title: '头像上传',
    message:
    '是否上传头像',
  })
    .then(() => {
      setTimeout(() => {
        fileInput.value!.click()
      })
    })
    .catch(() => {
    // on cancel
    })
}

async function fileUpload() {
  const img = fileInput.value!.files![0]
  const ok = await ContactApi.uploadAvatar(props.contact.id, img)
  if (ok) {
    showSuccessToast('上传成功')
    setTimeout(() => {
      location.reload()
    }, 500)
  }
  else {
    showFailToast('上传失败，请联系管理员')
  }
}

const getColor = Common.randomColor

onMounted(() => {
  fileInput.value!.addEventListener('change', fileUpload)
})

const isOverlayShown = ref(false)

function clickAvatar() {
  if (!props.canClick) {
    return
  }
  if (props.canUnload) {
    showUploadMenu()
  }
  else {
    isOverlayShown.value = true
  }
}
</script>

<template>
  <div style="width: fit-content;">
    <Overlay :show="isOverlayShown" flex-cc @click="isOverlayShown = false">
      <img
        v-if="contact.avatar"
        :src="contact.avatar"
        :alt="contact.name[0]"
        w-full object-fill
        @click.stop
      >
    </Overlay>
    <div
      :style="{
        height: `${0.25 * size}rem`,
        width: `${0.25 * size}rem`,
        backgroundColor: getColor(`${contact.name}${contact.phone}`),
      }"
      flex items-center justify-center of-hidden b-rd-1024 text-size-12 c-white
      @click="clickAvatar"
    >
      <img
        v-if="contact.avatar"
        :src="contact.avatar"
        :alt="contact.name[0]"
        h-full w-full object-cover
      >
      <div v-else :style="{ fontSize: `${2 * size}px` }">
        {{ contact.name[0] }}
      </div>
    </div>
    <input id="avatar" ref="fileInput" type="file" name="avatar" accept="image/*" hidden>
  </div>
</template>

<style scoped>

</style>
